package com.tcoiss.datafactory.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tcoiss.datafactory.domain.Test;
import com.tcoiss.datafactory.mapper.TestMapper;
//import com.tcoiss.datafactory.thread.BookThread;
import com.tcoiss.datafactory.thread.SyncBookHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Service
public class TestService extends ServiceImpl<TestMapper, Test> {

    private static final Logger log = LoggerFactory.getLogger(DynamicSqlServiceImpl.class);

    @Autowired
    private SyncBookHandler syncBookHandler;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    //核心线程数
    @Value("${book.core.poolsize}")
    private int threadSum;

    public void insetTest(){
        Long inserOrUpdateBegin = System.currentTimeMillis();
        log.info("数据更新开始时间:"+inserOrUpdateBegin/1000.0+"s");
        List<Test> bookList  = getPsrList();
        this.saveBatch(bookList);
        Long inserOrUpdateEnd = System.currentTimeMillis();
        log.info("数据更新结束时间:"+inserOrUpdateEnd/1000.0+"s。此次更新数据花费时间为："+(inserOrUpdateEnd-inserOrUpdateBegin)/1000.0+"s");
    }

    public void receiveBookJobRun(){
        List<Test> bookList  = getPsrList();
        //入库开始时间
        Long inserOrUpdateBegin = System.currentTimeMillis();
        log.info("数据更新开始时间:"+inserOrUpdateBegin/1000.0+"s");
        //接收集合各段的 执行的返回结果
        List<Future<String>> futureList = new ArrayList<Future<String>>();
        //集合总条数
        if(bookList != null){
            int listSize = bookList.size();

            int listStart,listEnd;
            //当总条数不足threadSum条时 用总条数 当做线程切分值
            if(threadSum > listSize){
                threadSum = listSize;
            }

            //将list 切分多份 多线程执行
            for (int i = 0; i < threadSum; i++) {
                //计算切割  开始和结束
                listStart = listSize / threadSum * i ;
                listEnd = listSize / threadSum * ( i + 1 );
                //最后一段线程会 出现与其他线程不等的情况
                if(i == threadSum - 1){
                    listEnd = listSize;
                }
                //数据切断
                List<Test> sunList = bookList.subList(listStart,listEnd);

                //每段数据集合并行入库
                futureList.add(syncBookHandler.syncMargePsr(sunList,i));

            }

            //对各个线程段结果进行解析
            for(Future<String> future : futureList){

                String str ;
                if(null != future ){
                    try {
                        str = future.get().toString();
                        log.info("current thread id ="+Thread.currentThread().getName()+",result="+str);

                    } catch (InterruptedException | ExecutionException e) {

                        log.info("线程运行异常！");
                    }

                }else{
                    log.info("线程运行异常！");
                }

            }
        }



        Long inserOrUpdateEnd = System.currentTimeMillis();
        log.info("数据更新结束时间:"+inserOrUpdateEnd/1000.0+"s。此次更新数据花费时间为："+(inserOrUpdateEnd-inserOrUpdateBegin)/1000.0+"s");

    }

//    public void ReceivePsrJobRun(){
//
//        List<Test> bookList = null;
//
//
//        bookList = getPsrList();
//        //接收集合各段的 执行的返回结果
//        List<Future<String>> futureList = new ArrayList<Future<String>>();
//        //集合总条数
//        int size = bookList.size();
//        //将集合切分的段数(2*CPU的核心数)
//        int sunSum = 2*Runtime.getRuntime().availableProcessors();
//        int listStart,listEnd;
//        //当总条数不足sunSum条时 用总条数 当做线程切分值
//        if(sunSum > size){
//            sunSum = size;
//        }
//
//        //定义子线程
//		/*BookThread bookThread;*/
//
//        //将list 切分多份 多线程执行
//        for (int i = 0; i < sunSum; i++) {
//            //计算切割  开始和结束
//            listStart = size / sunSum * i ;
//            listEnd = size / sunSum * ( i + 1 );
//            //最后一段线程会 出现与其他线程不等的情况
//            if(i == sunSum - 1){
//                listEnd = size;
//            }
//            //线程切断**/
//            List<Test> sunList = bookList.subList(listStart,listEnd);
//            //子线程初始化
//            BookThread bookThread = new BookThread(i,sunList);
//
//            //多线程执行
//            futureList.add((Future<String>) taskExecutor.submit((Runnable) bookThread));
//        }
//        System.out.println("----------1111111111");
//        //对各个线程段结果进行解析
//        for(Future<String> future : futureList){
//            try {
//                String str ;
//                if(null != future ){
//                    str = future.get().toString();
//                    System.out.println("##############current thread id ="+Thread.currentThread().getName()+",result="+str);
//                }else{
//                    System.err.println("失败");
//                }
//            } catch (InterruptedException | ExecutionException e) {
//
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//
//            }
//        }
//        System.out.println("----------2222");
//
//    }

    public List<Test> getPsrList(){
        List<Test> psrList = new ArrayList<Test>();
        for(int i=0 ; i<500000 ;i++){
            Test book = new Test();
            book.setName("zxl"+i);
            book.setNum(i);
            psrList.add(book);
        }

        return psrList;
    }
}
